﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Omu.Awesome.Mvc;

namespace Icms.WebUI.Controllers
{
    [Authorize]
    public class InboxController : BaseController
    {
        private readonly IRepo<Message> messageRepo;

        public InboxController(IRepo<Message> messageRepo)
        {
            this.messageRepo = messageRepo;
        }

        public virtual ActionResult Search(string search, bool? isread, int page = 1, int ps = 5)
        {
            var userId = Globals.User().Id;
            var src = messageRepo.Where(o => o.RecipientId == userId && o.Subject.Contains(search));
            if (isread.HasValue) src = src.Where(o => o.IsRead == isread.Value);

            var rows = this.RenderView("rows", src.OrderByDescending(o => o.DateSent).Pag(page, ps));

            return Json(new { rows, more = src.Count() > page * ps });
        }

        public virtual ActionResult Index()
        {
            ViewBag.DisableCreate = true;
            return View("cruds");
        }

        public virtual ActionResult Row(Guid id)
        {
            return View("rows", new[] { messageRepo.Get(id) });
        }

        public virtual ActionResult Read(Guid id)
        {
            var m = messageRepo.Get(id);
            m.IsRead = true;
            m.IsRecipientNotified = true;
            messageRepo.Save();
            return View(m);
        }
    }
}